package com.start_eternity.oasissafewalk.config;

import org.springframework.context.annotation.Configuration;

import java.io.*;
import java.nio.file.*;
import java.util.concurrent.locks.*;
@Configuration
public class OrderNoGenerator {

    private static final String ORDER_NO_FILE = "order_no.txt";
    private static final Lock lock = new ReentrantLock();
    private static int orderNo;

    static {
        // 初始化时从文件读取序号
        try {
            File file = new File(ORDER_NO_FILE);
            if (file.exists()) {
                String content = new String(Files.readAllBytes(Paths.get(ORDER_NO_FILE)));
                orderNo = Integer.parseInt(content.trim());
            } else {
                orderNo = 7; // 初始序号设置为5，因为下一个将是6
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to initialize order number", e);
        }
    }

    public String generateOrderNo() {
        lock.lock();
        try {
            orderNo++;
            // 序号自增后写入到文件
            BufferedWriter writer = new BufferedWriter(new FileWriter(ORDER_NO_FILE));
            writer.write(String.valueOf(orderNo));
            writer.close();
            return String.format("ORD%03d", orderNo);
        } catch (IOException e) {
            throw new RuntimeException("Failed to generate order number", e);
        } finally {
            lock.unlock();
        }
    }
}